<template>
  <!-- 顶部商店bar -->
  <div class="store-box">
    <div class="store-wrap">
      <img @dragstart.prevent class="store-img" :src="storeHeadshotUrl" />
      <span class="store-name">
        <p style="margin-bottom: 10px;">{{ storeInfo.storeVo.storeName }}</p>
        <el-tag size="small" round>shop</el-tag>
      </span>
      <!-- 竖直分割线 -->
      <el-divider direction="vertical" style="height: 30px; border: 1px solid gray" />
      <!-- 活动信息 -->
      <div class="activity">
        <div v-if="currentActivity.activity.status === 1">
          <span class="activity-name">
            🎉 {{ currentActivity.activity.activityName }}
          </span>
          <span class="activity-info">
            惊喜特惠，全场满
            <span class="activity-number">{{ currentActivity.activity.reach }}</span>
            元，立减
            <span class="activity-number">{{ currentActivity.activity.reduce }}</span>
            元
          </span>
        </div>
      </div>
    </div>

    <el-button icon="Shop" round class="into-shop-button" @click="enterStore()">进入店铺</el-button>
  </div>

  <!-- 商品信息 -->
  <div class="commodity-box">

    <div style="display: flex;" v-if="loading">

      <el-skeleton style="padding: 15px; width: 500px;" animated>
        <template #template>
          <el-skeleton-item variant="image" style="width: 450px; height: 450px;" />
          <div style="padding: 14px; width: 240px;">
            <el-skeleton-item variant="p" style="width: 50%" />
            <div style="display: flex; align-items: center; justify-items: space-between;">
              <el-skeleton-item variant="text" style="margin-right: 16px; " />
              <el-skeleton-item variant="text" style="width: 30%" />
            </div>
          </div>
        </template>
      </el-skeleton>

      <div style="display: flex; padding-top: 15px; flex-direction: column; width: 55%">
        <el-skeleton>
          <template #template>
            <el-skeleton-item variant="button" style="width: 25%;" />
          </template>
        </el-skeleton>

        <el-skeleton :rows="5" style="margin-top: 30px;" animated />

        <el-skeleton>
          <template #template>
            <el-skeleton-item variant="text" style="width: 35%; margin-top: 20px;" />
          </template>
        </el-skeleton>

        <el-skeleton>
          <template #template>
            <el-skeleton-item variant="text" style="width: 35%; margin-top: 20px;" />
          </template>
        </el-skeleton>
      </div>

    </div>

    <!-- 商品主要信息 -->
    <div class="commodity-main" v-else>

      <!-- 浏览图片 -->
      <div class="pic-gallery">
        <!-- 大图 -->
        <div class="big-img-box">
          <img @dragstart.prevent class="big-img" :src="img_url_pre(commodityInfo.commodity.pictures[curPicIndex + 1])" />
        </div>
        <!-- 小图横列表 -->
        <div class="small-img-box">
          <ul class="small-img-ul">
            <li v-for="(item, index) in commodityInfo.commodity.pictures.slice(1).map(img_url_pre)" :key="index"
              @click="changeImg(index)" :style="{ border: index == curPicIndex ? activeBorder : '0' }">
              <img @dragstart.prevent class="small-img" :src="item" />
            </li>
          </ul>
        </div>
      </div>

      <!-- 右侧商品名等 -->
      <div class="commodity-info">
        <h1 style="font-size: 25px; font-weight: 600; margin-bottom: 10px">
          {{ commodityInfo.commodity.commodityName }}
        </h1>
        <p style="font-size: 15px; color: #A2A2A2;">
          总销量 {{ commodityInfo.commodity.salesVolume }}
        </p>
        <p class="price">
          <span style="font-size: 13px;">售价</span>
          <span style="font-size: 16px;">￥</span>
          <span style="font-size: 28px; text-shadow: 2px 2px 2px rgba(10, 0, 50, 0.3);">
            {{ commodityInfo.commodity.price.toFixed(2) }}
          </span>
        </p>

        <div class="launch-date">
          <div style="font-size: 15px; color: #A2A2A2;">上架日期：</div>
          <div style="margin-left: 8px;">{{ commodityInfo.commodity.launchDate }}</div>
        </div>

        <div class="description">
          <div style="font-size: 15px; color: #A2A2A2;">商品简介：</div>
          <div class="detail">
            {{ commodityInfo.commodity.description }}
          </div>
        </div>

        <div class="category">
          <div style="font-size: 15px; color: #A2A2A2;">商品类型：</div>
          <div style="margin-left: 8px;">
            <el-tag style="font-size: 15px; height: 36px;" effect="light">
              {{ categoryInfo.category.categoryName }}
            </el-tag>
          </div>
        </div>

        <div class="stocks">
          <div style="font-size: 15px; color: #A2A2A2;">库存量：</div>
          <div style="margin-left: 23px;">{{ commodityInfo.commodity.stocks }}</div>
        </div>

        <div class="commodity-num">
          <div style="font-size: 15px; color: #A2A2A2;">数量：</div>
          <el-input-number style="margin-left: 40px; height: 37px;" v-model="curCommodityNum" :min="1" :max="10000000"
            :disabled="cart_loading">
          </el-input-number>
        </div>

        <div class="activity-in-box">
          <div class="head">
            <h1>满减活动</h1>
          </div>
          <div v-if="currentActivity.activity.status === 1 && inActivity" class="in-activity">
            🎉 {{ currentActivity.activity.activityName }}：
            满
            <span>{{ currentActivity.activity.reach }}</span>
            减
            <span>{{ currentActivity.activity.reduce }}</span>
          </div>
          <div v-else class="no-activiy">
            很抱歉，该商品没有优惠
          </div>
        </div>

        <el-button-group class="buttons">
          <el-button loading-icon="Loading" :loading="false" :disabled="cart_loading" class="l-button" size="large"
            type="primary" plain round @click="toPreview">
            <font-awesome-icon :icon="['fas', 'coins']" style="margin-right: 7px;" />
            立即购买
          </el-button>
          <el-button loading-icon="Loading" :loading="cart_loading" class="r-button" size="large" type="warning" plain
            round @click="addToCart">
            <font-awesome-icon v-if="!cart_loading" :icon="['fas', 'cart-plus']" style="margin-right: 7px;" />
            加入购物车
          </el-button>
        </el-button-group>
      </div>

    </div>
  </div>
</template>

<script setup>
import { ref, reactive, getCurrentInstance, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import img_url_pre from '../../utils/img_url_filter'

const router = useRouter();
const { proxy } = getCurrentInstance();
const store = useStore();
const activeBorder = '2px solid #8EB5D9';
const storeHeadshotUrl = ref('');
const inActivity = ref(false);  // 该商品是否在活动商品类型范围内

const currentActivity = reactive({
  activity: {
    "activityId": "",
    "activityName": "",
    "startTime": "",
    "endTime": "",
    "categoryIdList": [],
    "fund": 0,
    "reach": 0,
    "reduce": 0,
    "balance": 0,
    "registeredCapital": 0,
    "monthlySalesVolume": 0,
    "monthlySalesValue": 0,
    "status": 0
  }
});

const storeInfo = reactive({
  storeVo: {
    storeId: '',
    storeName: '',
    category: [],
    storeProfile: '',
    filingAddress: '',
    registeredCapital: 0,
    registrationDate: '',
    activityId: '',
    pictures: [],
    status: 1
  }
});
const commodityInfo = reactive({
  commodity: {
    commodityId: '',
    storeId: '',
    commodityName: '',
    categoryId: '',
    price: 0.0,
    pictures: [],
    description: '',
    salesVolume: 0,
    stocks: 0,
    launchDate: '',
    status: 0
  }
});
const categoryInfo = reactive({
  category: {
    categoryId: '',
    categoryName: '',
  }
})
const curPicIndex = ref(0)
const curCommodityNum = ref(1)
const cart_loading = ref(false)
const loading = ref(false)

// 获取商店展示信息
const getStoreVo = async (storeId) => {
  let res = await proxy.$api.store.getStoreVo(storeId);
  storeInfo.storeVo = res.data;
  storeHeadshotUrl.value = img_url_pre(res.data.pictures[0]);

  if (storeInfo.storeVo.activityId && storeInfo.storeVo.activityId.length > 0 && storeInfo.storeVo.activityId !== '0') {
    await getActivityInfo(storeInfo.storeVo.activityId);
  }
}

/**
 * 获取活动详情
 */
const getActivityInfo = async (activityId) => {
  let ret = await proxy.$api.activity.getActivityInfo(activityId);
  currentActivity.activity = ret.data;
}

// 获取商品信息
const getCommodity = async (commodityId) => {
  let res = await proxy.$api.commodity.getCommodity(commodityId);
  commodityInfo.commodity = res.data;
}

// 获取商品类别
const getCategory = async (categoryId) => {
  let res = await proxy.$api.category.getCategory(categoryId);
  categoryInfo.category = res.data;
}

// 加入购物车
const addToCart = async () => {
  // 开启按钮加载
  cart_loading.value = true;
  if (!store.state.user.userId) {
    router.push('/login')
  } else {
    // 发起请求
    let res = await proxy.$api.cart.addToCart({
      userId: store.state.user.userId,
      commodityId: commodityInfo.commodity.commodityId,
      storeId: commodityInfo.commodity.storeId,
      commodityNum: curCommodityNum.value,
    }).catch(error => {
      console.log(error);
      // 关闭按钮加载
      cart_loading.value = false;
    })
    if (res) {
      ElMessage.success({
        showClose: true,
        message: '加入购物车成功',
      })
    }

    // 关闭按钮加载
    cart_loading.value = false;
  }
}

// 改变大图
const changeImg = (index) => {
  curPicIndex.value = index;
}

// 进入商店
const enterStore = () => {
  router.push('/mall/store');
}

/**
 * 前往订单预览界面
 */
const toPreview = () => {
  let commodityGroup = [];
  commodityGroup.push([]);
  commodityGroup[0].push({
    storeVo: storeInfo.storeVo,
    commodity: commodityInfo.commodity,
    commodityNum: curCommodityNum.value,
  })

  store.commit('order/setCommodityGroup', commodityGroup);
  // 清空cartItemIdList，便于等一下提交订单的时候
  // 区分“直接购买”和“购物车结算”
  store.commit('order/clearCartItemIdList');

  if (store.state.order.toPreview !== true) {
    store.commit('order/reverseToPreview');
  }

  router.push('/mall/order/preview');
}

/**
 * 判断该商品是否在活动范围内
 */
const judgeInActivity = () => {
  if (currentActivity.activity.categoryIdList.length > 0) {
    for (let categoryId of currentActivity.activity.categoryIdList) {
      if (categoryId === commodityInfo.commodity.categoryId) {
        inActivity.value = true;
        return;
      }
    }
  }
}

onMounted(async () => {
  loading.value = true;

  await getCommodity(store.state.commodity.commodityId);
  await getStoreVo(commodityInfo.commodity.storeId);
  await getCategory(commodityInfo.commodity.categoryId);
  judgeInActivity();

  loading.value = false;
})

</script>

<style lang="less" scoped>
.store-box {
  width: 73%;
  height: 80px;
  background-color: rgb(255, 255, 255);
  margin: 10px auto 13px auto;
  border-radius: 40px;

  display: flex;
  justify-content: space-between;
  align-items: center;

  .store-wrap {
    display: flex;
    width: 80%;
    align-items: center;

    .store-img {
      height: 60px;
      width: 60px;
      border-radius: 35px;
      margin-left: 10px;
    }

    .store-name {
      margin-left: 10px;
      margin-right: 20px;

      p {
        font-size: 20px;
        font-weight: bold;
      }
    }

    .activity {
      margin-right: 20px;

      .activity-name {
        font-size: 20px;
        margin-right: 10px;
      }

      .activity-info {
        color: gray;

        .activity-number {
          font-size: 19px;
          color: #2e64c2;
        }
      }
    }
  }

  .into-shop-button {
    margin-right: 20px;
    height: 35px;
    width: 95px;
  }
}

.commodity-box {
  width: 73%;
  background-color: white;
  margin: 0 auto 0 auto;
  border-radius: 20px;

  .commodity-main {
    display: flex;
    padding: 15px;

    .pic-gallery {

      .big-img-box {
        .big-img {
          border-radius: 10px;
          height: 450px;
          width: 450px;
        }
      }

      .small-img-box {
        .small-img-ul {
          display: flex;
          margin-top: 10px;
          justify-content: center;

          li {
            margin-left: 7px;
            border-radius: 5px;
            border: 1px solid rgba(103, 102, 102, 0.459);
            height: 75px;
            width: 75px;
            display: flex;
            align-items: center;
            justify-content: center;
            background: #d3dae33a;

            .small-img {
              height: 60px;
              width: 60px;
            }
          }
        }
      }
    }

    .commodity-info {
      margin-left: 25px;
      width: 62%;

      .price {
        margin-top: 20px;
      }

      .launch-date {
        display: flex;
        margin-top: 30px;
      }

      .description {
        display: flex;
        margin-top: 30px;

        .detail {
          margin-left: 8px;
          width: 87%;
          font-size: 18px;
          letter-spacing: 1px;
        }
      }

      .category {
        display: flex;
        margin-top: 30px;
        align-items: center;
      }

      .stocks {
        display: flex;
        margin-top: 30px;
      }

      .commodity-num {
        display: flex;
        margin-top: 30px;
        align-items: center;
      }

      .activity-in-box {
        width: 350px;
        // height: 120px;
        border: 1px solid rgb(255, 67, 83);
        margin-top: 30px;

        .head {
          width: 100%;
          height: 35px;
          background: rgb(255, 67, 83);
          color: white;
          text-align: center;

          h1 {
            line-height: 35px;
          }
        }

        .in-activity {
          // font-size: 15px;
          color: rgb(255, 67, 83);
          text-align: center;
          line-height: 35px;
        }

        .no-activiy {
          color: rgb(255, 67, 83);
          text-align: center;
          height: 35px;
          line-height: 35px;
        }
      }

      .buttons {
        margin-top: 40px;
        margin-left: 85px;

        .l-button {
          height: 50px;
          width: 140px;
          border-radius: 25px 0 0 25px;
          font-size: 18px;
          font-weight: 600;
          box-shadow: 4px 9px 3px rgba(146, 188, 214, 0.1);
        }

        .r-button {
          height: 50px;
          width: 150px;
          border-radius: 0 25px 25px 0;
          font-size: 18px;
          font-weight: 600;
          box-shadow: 4px 9px 3px rgba(212, 178, 127, 0.1);
        }
      }
    }
  }

}
</style>